package org.dromara.common.model;

import com.alibaba.fastjson2.JSON;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * OKHttp使用工具类
 * @author Stars
 */
public class OkHttpUtils {

    // 手动创建静态的 Logger 实例
    private static final Logger log = LoggerFactory.getLogger(OkHttpUtils.class);

    private static final OkHttpClient okHttpClient;

    static {
        // 初始化 OkHttpClient 并设置超时时间
        okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .build();
    }

    /**
     * 发送推送消息
     *
     * @param map
     * @return
     */
    public static Response post(String url, Map<String, Object> map) throws IOException {
        //请求参数
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(map));
        Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
        final Call call = okHttpClient.newCall(request);
        return call.execute();
//            Response response = call.execute();
//            int code = response.code();
//            response.body().string();
    }

    /**
     * get请求发送
     *
     * @param url
     * @param map
     * @return
     */
    public static Response get(String url, Map<String, Object> map) throws IOException {
        //请求参数
        Request request = new Request.Builder()
            .url(appendUrl(url, map))
            .get()
            .build();
        final Call call = okHttpClient.newCall(request);
        return call.execute();
    }

    /**
     * 发送Get请求
     * @param url
     * @param map
     * @param headers
     * @return
     * @throws IOException
     */
    public static Response get(String url, Map<String, Object> map, Map<String, String> headers) throws IOException {
        // 构建请求
        Request.Builder requestBuilder = new Request.Builder()
            .url(appendUrl(url, map))
            .get();

        // 设置 headers
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        Request request = requestBuilder.build();
        final Call call = okHttpClient.newCall(request);
        return call.execute();
    }

    /**
     * 拼接Get的Url请求地址
     *
     * @param url
     * @param params
     * @return
     */
    private static String appendUrl(String url, Map<String, Object> params) {
        if (params == null || params.isEmpty()) {
            return url;
        }

        StringBuilder builder = new StringBuilder(url);
        boolean isFirst = true;
        for (String key : params.keySet()) {
            if (key != null && params.get(key) != null) {
                if (isFirst) {
                    isFirst = false;
                    builder.append("?");
                } else {
                    builder.append("&");
                }
                builder.append(key)
                    .append("=")
                    .append(params.get(key));
            }
        }
        return builder.toString();
    }
}
